package com.example.mockapiservice.config;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    // 预设的有效token
    private static final String VALID_TOKEN = "1234568-8978997";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                            Object handler) throws Exception {
        
        // 获取请求头中的token
        String token = request.getHeader("token");
        
        // 验证token
        if (token == null || !token.equals(VALID_TOKEN)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json");
            response.getWriter().write("{\"error\":\"Unauthorized: Invalid or missing token\"}");
            return false;
        }
        
        // token验证通过，继续处理请求
        return true;
    }
}